package com.newsplatform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.newsplatform.common.Constants;
import com.newsplatform.common.Result;
import com.newsplatform.dto.NewsRequest;
import com.newsplatform.entity.News;
import com.newsplatform.service.NewsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 新闻控制器
 * 
 * @author Logan.Li
 */
@Tag(name = "新闻管理", description = "新闻相关接口")
@RestController
@RequestMapping("/api/news")
@RequiredArgsConstructor
public class NewsController {
    
    private final NewsService newsService;
    
    /**
     * 分页查询新闻
     */
    @Operation(summary = "分页查询新闻")
    @GetMapping
    public Result<Map<String, Object>> getNewsPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String keyword) {
        
        IPage<News> newsPage = newsService.getNewsPage(page, size, status, categoryId, keyword);
        
        Map<String, Object> data = new HashMap<>();
        data.put("count", newsPage.getTotal());
        data.put("total_pages", newsPage.getPages());
        data.put("current_page", newsPage.getCurrent());
        data.put("page_size", newsPage.getSize());
        data.put("results", newsPage.getRecords());
        
        return Result.success(data);
    }
    
    /**
     * 获取新闻详情
     */
    @Operation(summary = "获取新闻详情")
    @GetMapping("/{id}")
    public Result<News> getNewsDetail(@PathVariable Long id) {
        News news = newsService.getById(id);
        if (news == null) {
            return Result.error("新闻不存在");
        }
        
        // 增加浏览次数
        newsService.incrementViewCount(id);
        
        return Result.success(news);
    }
    
    /**
     * 创建新闻
     */
    @Operation(summary = "创建新闻")
    @PostMapping
    public Result<News> createNews(@Valid @RequestBody NewsRequest request, Authentication authentication) {
        try {
            String username = authentication.getName();
            News news = newsService.createNews(request, username);
            return Result.success(news);
        } catch (Exception e) {
            return Result.error("创建新闻失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新新闻
     */
    @Operation(summary = "更新新闻")
    @PutMapping("/{id}")
    public Result<News> updateNews(@PathVariable Long id, @Valid @RequestBody NewsRequest request, Authentication authentication) {
        try {
            String username = authentication.getName();
            News news = newsService.updateNews(id, request, username);
            return Result.success(news);
        } catch (Exception e) {
            return Result.error("更新新闻失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除新闻
     */
    @Operation(summary = "删除新闻")
    @DeleteMapping("/{id}")
    public Result<Void> deleteNews(@PathVariable Long id, Authentication authentication) {
        try {
            News news = newsService.getById(id);
            if (news == null) {
                return Result.error("新闻不存在");
            }
            
            newsService.removeById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除新闻失败：" + e.getMessage());
        }
    }
    
    /**
     * 发布新闻
     */
    @Operation(summary = "发布新闻")
    @PostMapping("/{id}/publish")
    public Result<Void> publishNews(@PathVariable Long id, Authentication authentication) {
        try {
            String username = authentication.getName();
            newsService.publishNews(id, username);
            return Result.success();
        } catch (Exception e) {
            return Result.error("发布新闻失败：" + e.getMessage());
        }
    }
    
    /**
     * 点赞新闻
     */
    @Operation(summary = "点赞新闻")
    @PostMapping("/{id}/like")
    public Result<Void> likeNews(@PathVariable Long id) {
        try {
            newsService.likeNews(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("点赞失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取热门新闻
     */
    @Operation(summary = "获取热门新闻")
    @GetMapping("/hot")
    public Result<Map<String, Object>> getHotNews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        IPage<News> newsPage = newsService.getHotNews(page, size);
        
        Map<String, Object> data = new HashMap<>();
        data.put("count", newsPage.getTotal());
        data.put("total_pages", newsPage.getPages());
        data.put("current_page", newsPage.getCurrent());
        data.put("page_size", newsPage.getSize());
        data.put("results", newsPage.getRecords());
        
        return Result.success(data);
    }
    
    /**
     * 归档新闻
     */
    @Operation(summary = "归档新闻")
    @PostMapping("/{id}/archive")
    public Result<Void> archiveNews(@PathVariable Long id, Authentication authentication) {
        try {
            String username = authentication.getName();
            newsService.archiveNews(id, username);
            return Result.success();
        } catch (Exception e) {
            return Result.error("归档新闻失败：" + e.getMessage());
        }
    }
    
    /**
     * 置顶/取消置顶新闻
     */
    @Operation(summary = "置顶/取消置顶新闻")
    @PostMapping("/{id}/top")
    public Result<Void> toggleTopNews(@PathVariable Long id, @RequestParam Boolean isTop, Authentication authentication) {
        try {
            String username = authentication.getName();
            newsService.toggleTopNews(id, isTop, username);
            return Result.success();
        } catch (Exception e) {
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除新闻
     */
    @Operation(summary = "批量删除新闻")
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteNews(@RequestBody java.util.List<Long> ids, Authentication authentication) {
        try {
            String username = authentication.getName();
            newsService.batchDeleteNews(ids, username);
            return Result.success();
        } catch (Exception e) {
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取最新新闻
     */
    @Operation(summary = "获取最新新闻")
    @GetMapping("/latest")
    public Result<Map<String, Object>> getLatestNews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        IPage<News> newsPage = newsService.getLatestNews(page, size);
        
        Map<String, Object> data = new HashMap<>();
        data.put("count", newsPage.getTotal());
        data.put("total_pages", newsPage.getPages());
        data.put("current_page", newsPage.getCurrent());
        data.put("page_size", newsPage.getSize());
        data.put("results", newsPage.getRecords());
        
        return Result.success(data);
    }
    
    /**
     * 获取推荐新闻
     */
    @Operation(summary = "获取推荐新闻")
    @GetMapping("/recommended")
    public Result<Map<String, Object>> getRecommendedNews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        IPage<News> newsPage = newsService.getRecommendedNews(page, size);
        
        Map<String, Object> data = new HashMap<>();
        data.put("count", newsPage.getTotal());
        data.put("total_pages", newsPage.getPages());
        data.put("current_page", newsPage.getCurrent());
        data.put("page_size", newsPage.getSize());
        data.put("results", newsPage.getRecords());
        
        return Result.success(data);
    }
    
}
